package org.wm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.wm.constants.UserConstants;
import org.wm.entity.*;
import org.wm.exception.ServiceException;
import org.wm.mapper.*;
import org.wm.service.ISysUserService;
import org.wm.utils.SecurityUtils;
import org.wm.utils.SpringUtils;
import org.wm.utils.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 * (已按照 Mybatis-Plus 混合模式进行改造)
 */
@RequiredArgsConstructor
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    private final SysRoleMapper roleMapper;
    private final SysPostMapper postMapper;
    private final SysUserRoleMapper userRoleMapper;
    private final SysUserPostMapper userPostMapper;

    @Override
    public IPage<SysUser> selectUserPage(Page<SysUser> page, SysUser user) {
        return baseMapper.selectUserPage(page, user);
    }

    @Override
    public IPage<SysUser> selectAllocatedList(Page<SysUser> page, SysUser user) {
        return baseMapper.selectAllocatedList(page, user);
    }

    @Override
    public IPage<SysUser> selectUnallocatedList(Page<SysUser> page, SysUser user) {
        return baseMapper.selectUnallocatedList(page, user);
    }

    @Override
    public SysUser selectUserByUserName(String userName) {
        return baseMapper.selectUserByUserName(userName);
    }

    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) { return StringUtils.EMPTY; }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) { return StringUtils.EMPTY; }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    @Override
    public String checkUserNameUnique(String userName) {
        long count = this.count(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, userName));
        return count > 0 ? UserConstants.NOT_UNIQUE : UserConstants.UNIQUE;
    }

    @Override
    public String checkPhoneUnique(SysUser user) {
        Long userId = user.getUserId() == null ? -1L : user.getUserId();
        SysUser info = this.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getPhonenumber, user.getPhonenumber()));
        if (info != null && !info.getUserId().equals(userId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String checkEmailUnique(SysUser user) {
        Long userId = user.getUserId() == null ? -1L : user.getUserId();
        SysUser info = this.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getEmail, user.getEmail()));
        if (info != null && !info.getUserId().equals(userId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public void checkUserAllowed(SysUser user) {
        if (user.getUserId() != null && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    @Override
    public void checkUserDataScope(Long userId) {
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = baseMapper.selectUserListByDataScope(user);
            if (users.isEmpty()) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    @Override
    @Transactional
    public boolean insertUser(SysUser user) {
        boolean result = this.save(user);
        if (result) {
            insertUserPost(user);
            insertUserRole(user);
        }
        return result;
    }

    @Override
    public boolean registerUser(SysUser user) {
        return this.save(user);
    }

    @Override
    @Transactional
    public boolean updateUser(SysUser user) {
        Long userId = user.getUserId();
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(user);
        userPostMapper.deleteUserPostByUserId(userId);
        insertUserPost(user);
        return this.updateById(user);
    }

    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    @Override
    public boolean updateUserStatus(SysUser user) {
        return this.update(new LambdaUpdateWrapper<SysUser>()
                .eq(SysUser::getUserId, user.getUserId())
                .set(SysUser::getStatus, user.getStatus()));
    }

    @Override
    public boolean updateUserProfile(SysUser user) {
        if (user == null || user.getUserId() == null) { return false; }
        LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysUser::getUserId, user.getUserId());
        updateWrapper.set(user.getLoginIp() != null, SysUser::getLoginIp, user.getLoginIp());
        updateWrapper.set(user.getLoginDate() != null, SysUser::getLoginDate, user.getLoginDate());
        return this.update(updateWrapper);
    }

    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return this.update(new LambdaUpdateWrapper<SysUser>()
                .eq(SysUser::getUserName, userName)
                .set(SysUser::getAvatar, avatar));
    }

    @Override
    public boolean resetUserPwd(String userName, String password) {
        return this.update(new LambdaUpdateWrapper<SysUser>()
                .eq(SysUser::getUserName, userName)
                .set(SysUser::getPassword, password));
    }

    @Override
    @Transactional
    public boolean deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
        }
        userRoleMapper.deleteUserRole(userIds);
        userPostMapper.deleteUserPost(userIds);
        return this.removeByIds(Arrays.asList(userIds));
    }

    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (userList == null || userList.isEmpty()) { throw new ServiceException("导入用户数据不能为空！"); }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = ""; // configService.selectConfigByKey("sys.user.initPassword");

        for (SysUser user : userList) {
            try {
                SysUser u = this.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, user.getUserName()));
                if (u == null) {
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUserName()).append(" 导入成功");
                } else if (isUpdateSupport) {
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUserName()).append(" 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、账号 ").append(user.getUserName()).append(" 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    // === 私有辅助方法 (基本保持不变) ===
    private void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (roles != null && roles.length > 0) {
            List<SysUserRole> list = new ArrayList<>();
            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (!list.isEmpty()) { userRoleMapper.batchUserRole(list); }
        }
    }

    private void insertUserRole(Long userId, Long[] roleIds) {
        if (roleIds != null && roleIds.length > 0) {
            List<SysUserRole> list = new ArrayList<>();
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (!list.isEmpty()) { userRoleMapper.batchUserRole(list); }
        }
    }

    private void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (posts != null && posts.length > 0) {
            List<SysUserPost> list = new ArrayList<>();
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (!list.isEmpty()) { userPostMapper.batchUserPost(list); }
        }
    }
}